package com.share.tool.mock.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.share.common.common.Page;
import com.share.common.utils.ThreadUtil;
import com.share.tool.mock.mapper.DbVariableMapper;
import com.share.tool.mock.model.db.DbVariable;
import com.share.tool.mock.model.db.Variable;
import com.share.tool.mock.model.dto.DbMockReq;
import com.share.tool.mock.model.dto.DbMockRsq;
import com.share.tool.mock.model.vo.DbPageListReq;
import com.share.tool.mock.service.DbVariableService;
import com.share.tool.mock.service.VariableService;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.sql.DataSource;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Service
public class DbVariableServiceImpl extends ServiceImpl<DbVariableMapper, DbVariable> implements DbVariableService {
    @Autowired
    private VariableService mockVariableService;

    @Autowired
    private DbVariableMapper mockDbVariableMapper;

    @Autowired
    @ApiModelProperty("直连使用Connection,spring中用DataSource")
    private DataSource dataSource;

    /**
     * 随机生成数据-并组装成insert语句
     *
     * @param req
     * @return
     */
    @Override
    public DbMockRsq dbMork(DbMockReq req) {
        String tableName = req.getTableName();
        if (StringUtils.isEmpty(tableName)) {
            return null;
        }

        LambdaQueryWrapper<DbVariable> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DbVariable::getTableName, tableName);
        List<DbVariable> columnList = mockDbVariableMapper.selectList(queryWrapper);
        if (CollectionUtils.isEmpty(columnList)) {
            return null;
        }

        String insertColumn = genInsertColumn(columnList);
        AtomicInteger total = new AtomicInteger(0);
        for (int i = 0; i < req.getBatchNum(); i++) {
            ThreadUtil.execute(new Runnable() {
                @Override
                public void run() {
                    //生成数据
                    List<Map<String, Object>> batchList = oneBatch(columnList, req.getOneBatchCycleNum());

                    if (!CollectionUtils.isEmpty(batchList)) {
                        //生成sql
                        String insertValue = genInsertValue(columnList, batchList);
                        String insertSql = insertColumn + insertValue;
                        log.info("待执行sql={}", insertSql);
                        //执行sql
                        try {
                            PreparedStatement pstat = dataSource.getConnection().prepareStatement(insertSql);
                            int insertCount = pstat.executeUpdate();
                            total.addAndGet(insertCount);
                        } catch (SQLException throwables) {
                            //直接抛出不处理
                            throw new RuntimeException(throwables);
                        }
                    }
                }
            });
        }
        DbMockRsq morkRsq = new DbMockRsq();
        morkRsq.setMessage("插入记录数:" + total.intValue());
        return morkRsq;
    }

    //生成sql头部
    private String genInsertColumn(List<DbVariable> columnList) {
        String tableName = columnList.get(0).getTableName();
        StringBuffer sbRecord = new StringBuffer();
        for (DbVariable column : columnList) {
            String value = column.getColumnName();
            sbRecord.append(",`" + value + "`");
        }
        sbRecord.deleteCharAt(0);
        sbRecord.insert(0, "insert into " + tableName + "(");
        sbRecord.append(") values ");
        return sbRecord.toString();
    }

    //生成sql语句直接入库
    private String genInsertValue(List<DbVariable> columnList, List<Map<String, Object>> dataList) {
        StringBuffer sbAll = new StringBuffer();
        for (Map<String, Object> map : dataList) {
            StringBuffer sbRecord = new StringBuffer();
            sbRecord.append("(");
            for (DbVariable column : columnList) {
                Object value = map.get(column.getColumnName());
                sbRecord.append(",'" + value + "'");
            }
            sbRecord.deleteCharAt(1);
            sbRecord.append(")");
            sbAll.append("," + sbRecord.toString());
        }
        sbAll.deleteCharAt(0);

        return sbAll.toString();
    }

    private List<Map<String, Object>> oneBatch(List<DbVariable> columnList, int batchCycleNum) {
        List<Map<String, Object>> batchList = new LinkedList();
        try {
            for (int i = 0; i < batchCycleNum; i++) {
                Map<String, Object> recordMap = new HashMap<>();
                for (DbVariable column : columnList) {
                    Variable morkVariable = mockVariableService.getByVariableCode(column.getVariable());
                    if (morkVariable == null) {
                        continue;
                    }

                    Object value = null;
                    try {
                        value = mockVariableService.exeGroovyScript(column.getVariable(), "parseJson", null);
                    } catch (Exception e) {
                        //异常不打印
                        value = morkVariable.getDefaultValue();
                    }

                    recordMap.put(column.getColumnName(), value);
                }
                batchList.add(recordMap);
            }
        } catch (Exception e) {
            log.error("生成数据异常", e);
        }
        return batchList;
    }

    @Override
    public Page pageList(DbPageListReq req) {
        PageHelper.startPage(req.getPageNum(), req.getPageSize());
        LambdaQueryWrapper<DbVariable> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(req.getColumnName())) {
            queryWrapper.like(DbVariable::getColumnName, req.getColumnName());
        }
        if (StringUtils.isNotBlank(req.getTableName())) {
            queryWrapper.like(DbVariable::getTableName, req.getTableName());
        }
        if (StringUtils.isNotBlank(req.getVariable())) {
            queryWrapper.like(DbVariable::getVariable, req.getVariable());
        }
        List<DbVariable> list = mockDbVariableMapper.selectList(queryWrapper);
        return new Page<>(list, new PageInfo<>(list).getTotal(), req);
    }
}
